#!/use/bin/python
# coding=utf-8
# 1.应用场景数 2.服务活跃率 3.服务调用量
import datetime
import pymysql
import json

import requests
from dbutils.pooled_db import PooledDB


# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.150.109', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

#根据传入的SQL 返回执行SQL返回的数量
def selectNumBySql(sql,conf=2):
    if conf == 1:
        conn, cur = getConfConnection()
    else:
        conn, cur = getDataConnection()
    #print(sql)
    cur.execute(sql)
    numResult = cur.fetchone()
    num = 0
    if numResult is not None:
        num = numResult[0]
    return num

#计算百分比 保留两位小数  如:34.88%
# X为分子 Y为分母
def getRateByXY(X,Y):
    rate = 0
    if Y != 0:
        if X > Y:
            rate = 100
        else:
            rate = round(X *100 / Y, 2)
    return rate

# 服务活跃率
def serviceActivityRate(date):
    try:
        conn, cur = getDataConnection()
        # 活跃率,单位:%
        #activityRate = selectNumBySql(
        #    f"select t.accuracy from analysis_intention t where t.ref_date = '{date}'")
        activityRate = 50
        logDetail = f"{date}日:服务活跃率百分比为:{activityRate}"
        print(logDetail)

        payload = json.dumps({
            "indexId": "T00204",
            "indexValue": f"{activityRate}",
            "dt": f"{date}",
            "indexType": "1",
            "dataReportingTeam": "智能平台技术"
        })
        headers = {
            'Content-Type': 'application/json'
        }
        print(payload)
        response = requests.request("POST", url, headers=headers, data=payload)

        print(response.text)

    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 服务月活
def serviceActivityData(date):
    try:
        conn, cur = getDataConnection()
        # 调用量,单位:次
        #callNum = selectNumBySql(
        #    f"select t.accuracy from analysis_intention t where t.ref_date = '{date}'")
        callNum = 6448361
        logDetail = f"{date}日:服务月活量为:{callNum}"
        print(logDetail)

        payload = json.dumps({
            "indexId": "T00203",
            "indexValue": f"{callNum}",
            "dt": f"{date}",
            "indexType": "1",
            "dataReportingTeam": "智能平台技术"
        })
        headers = {
            'Content-Type': 'application/json'
        }
        print(payload)
        response = requests.request("POST", url, headers=headers, data=payload)

        print(response.text)

    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 意图满足率
def intentSatisfactionRate(date):
    try:
        conn, cur = getDataConnection()
        # 调用量,单位:次
        #satisfactionRate = selectNumBySql(
        #    f"select t.accuracy from analysis_intention t where t.ref_date = '{date}'")
        satisfactionRate = 4.88
        logDetail = f"{date}日:意图满足率为:{satisfactionRate}"
        print(logDetail)

        payload = json.dumps({
            "indexId": "T00202",
            "indexValue": f"{satisfactionRate}",
            "dt": f"{date}",
            "indexType": "1",
            "dataReportingTeam": "智能平台技术"
        })
        headers = {
            'Content-Type': 'application/json'
        }
        print(payload)
        response = requests.request("POST", url, headers=headers, data=payload)

        print(response.text)

    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()


# 获取当前日期
def todayYMD():
    today = datetime.datetime.now()-1
    # 获取想要的日期的时间
    re_date = (today).strftime('%Y-%m-%d')
    return re_date


# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getMonthdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m')
    return re_date


if __name__ == '__main__':
    d = 1
    #date = getdate(d)
    date = "2024-03-29"
    #url = "http://192.168.2.176:8080/star-rocks/common/data/access/result" #测试
    url = "https://api-bdata.skysrt.com/star-rocks/common/data/access/result"  # 正式
    serviceActivityRate(date)
    #serviceActivityData(date)
    #intentSatisfactionRate(date)
    print (f"{date} 日期,上传到<1.应用场景数><2.服务活跃率><3.服务调用量><4.意图满足率>" )


